package com.tianyi.wz.walkinggame.views;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tianyi.wz.walkinggame.R;
import com.tianyi.wz.walkinggame.biz.CsjBannerBiz;
import com.tianyi.wz.walkinggame.biz.CsjRewardVideoBiz;
import com.tianyi.wz.walkinggame.biz.IBannerBiz;
import com.tianyi.wz.walkinggame.biz.IRewardVideoBiz;
import com.tianyi.wz.walkinggame.biz.TbsBannerBiz;
import com.tianyi.wz.walkinggame.biz.TbsRewardVideoBiz;

import org.apache.commons.lang3.StringUtils;

public class AdDialog extends Dialog {

    String userId;
    String codeId;
    FrameLayout adContainer;
    Activity activity;
    Boolean flag;
    TextView btnDialogClose;
    Boolean dismissFlag = false;
    String type;

    Handler handler;

    public void setBtnDialogClose(TextView btnDialogClose) {
        this.btnDialogClose = btnDialogClose;
    }

    public TextView getBtnDialogClose() {
        return btnDialogClose;
    }

    public Boolean getFlag() {
        return flag;
    }

    public void setFlag(Boolean flag) {
        this.flag = flag;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void setCodeId(String codeId) {
        this.codeId = codeId;
    }

    public void setAdContainer(FrameLayout adContainer) {
        this.adContainer = adContainer;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    public void setType(String type) {
        this.type = type;
    }

    public AdDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    public static class Builder {

        private View mLayout;

        Activity mActivity;
        String mUserId;
        String mCodeId;

        AdDialog mDialog;
        String mType;

        WebView webView;
        FrameLayout adContainer;
        TextView btnDialogClose;

        public Builder(Activity activity,String url,String userId,String codeId,String type) {
            mActivity = activity;
            mUserId = userId;
            mCodeId = codeId;
            mType = type;
            mDialog = new AdDialog(activity, R.style.CustomDialog);
            LayoutInflater inflater =
                    (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mLayout = inflater.inflate(R.layout.dialog_ad, null,false);
            mDialog.addContentView(mLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            webView = mDialog.findViewById(R.id.web_box);
            adContainer = mDialog.findViewById(R.id.ad_container);
            btnDialogClose = mDialog.findViewById(R.id.btn_dialog_close);
            btnDialogClose.setOnClickListener((View) -> mDialog.dismiss());
            mDialog.setActivity(activity);
            mDialog.setUserId(mUserId);
            mDialog.setCodeId(mCodeId);
            mDialog.setAdContainer(adContainer);
            mDialog.setBtnDialogClose(btnDialogClose);
            mDialog.setType(mType);
            initWebView(url);
        }

        /**
         * 腾讯 X5 加载网页
         */
        @SuppressLint("SetJavaScriptEnabled")
        private void initWebView(String url) {
            if (webView != null) {

                WebSettings settings = webView.getSettings();
                settings.setJavaScriptEnabled(true);
                settings.setDomStorageEnabled(true);
                webView.addJavascriptInterface(new AppInterface(), "appInterface");
                settings.setUserAgentString(settings.getUserAgentString() + " app/android/WalkingGame");

                webView.loadUrl(StringUtils.isEmpty(url)?"file:////android_asset/box.html":url);

                webView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                        webView.loadUrl(s);
                        return true;
                    }
                });

                webView.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onProgressChanged(WebView webView, int i) {
                        /*
                        if (i < 100) {
                            webView.setVisibility(View.GONE);
                        } else {
                            webView.setVisibility(View.VISIBLE);
                        }
                        */
                    }
                });
            }
        }

        public AdDialog create() {
            //mDialog.setCancelable(true);                //用户可以点击后退键关闭 Dialog
            //mDialog.setCanceledOnTouchOutside(true);   //用户不可以点击外部来关闭 Dialog
            return mDialog;
        }

        class AppInterface{

            @JavascriptInterface
            public void closeDialog(){
                mDialog.dismiss();
            }

            @JavascriptInterface
            public void popAdWithInspire(String userId,String portal,String codeId){
            /*
            Intent i = new Intent(activity,AdActivity.class);
            activity.startActivity(i);
            */

                mActivity.runOnUiThread(() -> {
                    IRewardVideoBiz biz = null;
                    if("toutiao".equals(portal)){
                        biz = CsjRewardVideoBiz.getInstance(mActivity,userId,codeId);
                    }else if("eqqads".equals(portal)){
                        biz = TbsRewardVideoBiz.getInstance(mActivity,userId,codeId);
                    }
                    if(biz!=null) {
                        biz.showAd();
                    }
                });

            }

        }

    }

    @Override
    public void show() {
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                getBtnDialogClose().setText(msg.arg1>0?""+msg.arg1:"X");
                super.handleMessage(msg);
            }
        };
        AdDialog.this.setFlag(false);
        IBannerBiz biz = null;
        if("toutiao".equals(type)){
            biz = CsjBannerBiz.getInstance(activity,adContainer,userId,codeId);
        }else if("eqqads".equals(type)){
            biz = TbsBannerBiz.getInstance(activity,adContainer,userId,codeId);
        }
        if(biz!=null) {
            biz.setCallback(() -> {
                //AdDialog.super.show();
                AdDialog.this.setFlag(true);
            });
            dismissFlag = false;
            new Thread(() -> {
                for (int i = 3; i >= 0; i--) {
                    try {
                        Message message = new Message();
                        message.arg1 = i;
                        handler.sendMessage(message);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                dismissFlag = true;
            }).start();
            biz.showAd();
            //adContainer.removeAllViews();
            //dismissFlag = true;
            //getBtnDialogClose().setText("X");
        }else{
            adContainer.removeAllViews();
        }
        super.show();
    }

    @Override
    public void dismiss() {
        if(dismissFlag) {
            super.dismiss();
        }
    }
}
